package com.binfenhulian.chinaenergy.ces.manage.controller.base;

import com.binfenhulian.chinaenergy.ces.core.exception.BaseException;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;

import javax.servlet.http.HttpServletRequest;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by wanghjbuf on 2018/3/14.
 */
public abstract class BaseController {

    /**
     * 转化request请求参数到Map
     * @param request
     * @return
     */
    public Map<String,Object> getParamMap(HttpServletRequest request ){
        Map<String,Object> paramMap = new HashMap<String,Object>();
        paramMap.put("pageNum", 1);
        paramMap.put("pageSize", 50);

        Enumeration<String> keys = request.getParameterNames();
        do{
            if(!keys.hasMoreElements())
                break;
            String key = (String)keys.nextElement();
            String value = request.getParameter(key);
            if(value != null && !value.equals("") && !value.equals("[]"))
                paramMap.put(key, value);
        } while(true);
        return paramMap;
    }

    /**
     * 获取验证类信息
     * @param bindingResult
     * @throws BaseException
     */
    public void getVaildErrors(BindingResult bindingResult) throws BaseException{

        if (bindingResult.hasErrors()){
            List<ObjectError> erros = bindingResult.getAllErrors();
            throw new BaseException(erros.get(0).getDefaultMessage());
        }
    }
}
